package com.sharding.jdbc.algorithm;


/**
 * @author Administrator
 * @version 1.0
 * @description: TODO
 * @date 2025/6/26 15:46
 */

import org.apache.shardingsphere.sharding.api.sharding.standard.RangeShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.StandardShardingAlgorithm;
import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue;

import java.util.*;

public class TaskIdShardingAlgorithm implements StandardShardingAlgorithm<Long> {

    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Long> shardingValue) {
        Long taskId = shardingValue.getValue();
        int size = availableTargetNames.size();
        int index = (int) (taskId % size);

        // JDK8风格，排序后取第index个
        Optional<String> target = availableTargetNames.stream()
                .sorted(Comparator.naturalOrder())
                .skip(index)
                .findFirst();

        return target.orElseThrow(() -> new IllegalArgumentException("No target table found for taskId: " + taskId));
    }

    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<Long> rangeShardingValue) {

        return new ArrayList<>();
    }


    @Override
    public String getType() {
        return "TASK_ID_MOD";
    }

    @Override
    public Properties getProps() {
        return null;
    }

    @Override
    public void init(Properties properties) {

    }
}